package com.yzh.usercenter.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yzh.usercenter.model.User;
import com.yzh.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 缓存预热
 */
@Component
@Slf4j
public class PreCacheJob {
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private RedissonClient redissonClient;
    //重点用户
    private List<Long> mainUserList = Arrays.asList(1L);
    //每天执行,预热推荐用户
    @Scheduled(cron = "0 18 22 * * *")
    public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock("xunyou:precachejob:docache:lock");
        try {
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                System.out.println("getLock: " + Thread.currentThread().getId());
                for (Long userId : mainUserList) {
                    QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
                    Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);
                    String redisKey = String.format("xunyou:user:recommend:%s", userId);
                    try {
                        redisTemplate.opsForValue().set(redisKey, userPage, 30, TimeUnit.MINUTES);
                    } catch (Exception e) {
                        log.error("set Redis失败: ", e);
                    }
                }
            }else {
                System.out.println("没获取");
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error: ", e);
        }finally {
            if (lock.isHeldByCurrentThread()) {
                System.out.println("unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }


    }
}
